<template>
	<view class="login_body">
		<!-- 头部应用名称 -->
		<view class="zgn">
			钓鱼翁
		</view>
		<!-- 登入表单 -->
		<view class="login-form" ref="form" :modelValue="formData">
			<view class="zai-item">
				<image src="../../static/img/whq/loginuser.png" class="icon"></image>
				<input class="zai-input" v-model="formData.username" placeholder-class placeholder="用户名" />
			</view>
			<view class="zai-item">
				<image src="../../static/img/whq/userpass.png" class="icon"></image>
				<input class="zai-input" v-model="formData.password" placeholder-class password placeholder="密码" />
			</view>
			<view class="btns">
				<button class="zai-btn" @click="submitForm">登录</button>
				<image src="../../static/img/whq/人脸.png" mode="" @click="getrenst"></image>
				<image src="../../static/img/whq/指纹.png" mode="" @click="fingerprint"></image>
			</view>
			<view class="zai-lun">
				<navigator url="/pages/login/register" hover-class="none" class="zai-label">还没有账号？点此注册.</navigator>
				<navigator url="/pages/login/forgetPass" hover-class="none" class="zai-label">忘记密码？</navigator>
			</view>
			<view class="third">第三方接口登录</view>
		</view>
		<view class="other">
			<view class="othor-item" @tap="loginOther('weixin')">
				<image src="../../static/img/whq/微信.png" mode=""></image>
			</view>
			<view class="othor-item" @tap="loginOther('sinaweibo')">
				<image src="../../static/img/whq/微博.png" mode=""></image>
			</view>
			<view class="othor-item" @tap="loginOther('qq')">
				<image src="../../static/img/whq/QQ.png" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script setup>
	// import {toBase64} from "@/common/base64.js"
	// import face from "@/uni_modules/mcc-face/index.js"
	// 引入的内容
	import {
		onMounted,
		reactive,
		ref
	} from 'vue';

	// 定义的存储变量
	const data = ref([])
	const formData = reactive({
		username: "",
		password: "",
	})
	const faceNum = ref(true)

	// 点击触发登入
	const submitForm = () => {
		if (formData.username !== '' && formData.password !== '') {
			onSignIn();
		} else {
			console.log('error submit!');
			return false;
		}
	};

	// 挂载阶段
	onMounted(() => {
		// uni.request({
		// 	url: 'http://127.0.0.1:3000/whq/getUser', //仅为示例，并非真实接口地址。
		// 	success: (res) => {
		// 		let data = [];
		// 		res.data.data.forEach((item) => {
		// 			item = JSON.parse(JSON.stringify(item).replace('_id', 'id'));
		// 			data.push(item);
		// 		});
		// 		restApi.findUsers(data);
		// 	}
		// });
	});

	// 账号密码登入
	const onSignIn = () => {
		uni.request({
			url: 'http://152.136.32.181:3080/whq/login',
			method: 'POST',
			data: {
				name: formData.username,
				password: formData.password
			},
			success: (res) => {
				console.log(res, 8888)
				if (res) {
					uni.setStorage({
						key: 'token',
						data: res.data.token,
					});
					uni.setStorage({
						key: 'data',
						data: res.data.data,
					});
					console.log('登入成功~')
					// let user = restApi.findUser(formData.username, formData.password);
					// uni.setStorageSync('currentUser', user);
					uni.switchTab({
						url: '/pages/tabbar/tabbar-1/tabbar-1'
					})
				} else {
					console.log('失败的回调', res.data.code)
				}
			}
		})
	};

	// 验证获取数据
	const getUserData = async () => {
		uni.request({
			url: 'http://152.136.32.181:3080/whq/list',
			method: "GET",
			success: (res) => {
				data.value = res.data
			},
		});
	}

	// 人脸识别
	const getrenst = () => {
		face.open(['a', 'b', 'c'], function(base64String) {
			if (faceNum.value == true) {
				uploadToServer(base64String)
				faceNum.value = false
			}
		})
		// uni.chooseImage({
		// 	sourceType: ['camera', 'album'], // 仅打开相机
		// 	success: (res) => {
		// 		const tempFilePaths = res.tempFilePaths;
		// 		compressAndUpload(tempFilePaths[0]);
		// 	},
		// 	fail: (err) => {
		// 		console.error('拍照失败', err);
		// 	}
		// });
	}

	// 压缩文件
	const compressAndUpload = (filePath) => {
		uni.compressImage({
			src: filePath,
			quality: 80,
			success: (res) => {
				const compressedFilePath = res.tempFilePath; // 获取压缩后的图片文件路径
				convertImageToBase64(compressedFilePath);
			},
			fail: (err) => {
				console.error('压缩图片失败', err);
			},
		});
	}

	// 转换base64
	const convertImageToBase64 = (filePath) => {
		toBase64(filePath).then(res => {
			uploadToServer(res)
		})
	}

	// 向后端发送请求
	const uploadToServer = (base64String) => {
		uni.showLoading({
			title: '识别中'
		});
		face.close() //关闭页面
		uni.request({
			url: 'http://152.136.32.181:3080/whq/face',
			method: "POST",
			data: {
				upload: base64String
			},
			success: (res) => {
				uni.hideLoading();
				uni.showToast({
					title: '识别成功',
					duration: 2000
				});
				if (res.data.code == 200) {
					uni.switchTab({
						url: '/pages/tabbar/tabbar-1/tabbar-1'
					})
				} else {
					uni.showLoading({
						title: '识别失败'
					});
				}
			},
			fail: (error) => {
				console.log(error)
			}
		})
	}

	// 第三方登入
	const loginOther = (mode) => {
		uni.login({
			provider: mode,
			success: (res) => {
				//最主要的就是openId
				let openId = res.authResult.openId;
				uni.getUserInfo({
					provider: mode,
					success: (res) => {
						console.log(res)
						let provider = mode;
						let openId = res.userInfo.openId;
						let avatar = res.userInfo.avatarUrl;
						let nickName = res.userInfo.nickName;
						uni.request({
							url: "http://152.136.32.181:3080/whq/loginother",
							method: "POST",
							data: {
								provider,
								openId,
								nickName,
								avatar
							},
							success: (res) => {
								if (res) {
									uni.setStorage({
										key: 'token',
										data: res.data.token,
									});
									uni.setStorage({
										key: 'data',
										data: res.data.data,
									});
									console.log('登入成功~')
									uni.switchTab({
										url: '/pages/tabbar/tabbar-1/tabbar-1'
									})
								} else {
									console.log('失败的回调', res.data.code)
								}
							}
						})
					}
				})
			}
		})
	}

	// 指纹识别
	const fingerprint = () => {
		// 获取手机上支持的生物认证
		uni.checkIsSupportSoterAuthentication({
			success(res) {
				// 弹出框 显示支持的认证方式 人脸 指纹
				// uni.showModal({
				// 	content: '支持的认证方式：' + res.supportMode,
				// 	showCancel: false
				// });
				// 获取设备内是否录入如指纹等生物信息的接口 checkIsSoterEnrolledInDevice
				uni.checkIsSoterEnrolledInDevice({
					checkAuthMode: 'fingerPrint',
					success(res) {
						if (res.isEnrolled) {
							// 判断是否录入指纹
							// uni.showToast({
							// 	icon: 'none',
							// 	title: '已录入指纹'
							// });
							// 开始 SOTER 生物认证 startSoterAuthentication
							uni.startSoterAuthentication({
								// OBJECT.requestAuthModes说明
								// 值	        说明
								// fingerPrint	指纹识别
								// facial	    人脸识别
								requestAuthModes: ['fingerPrint', 'facial'],
								challenge: '123456',
								authContent: '请用指纹解锁',
								// App端指纹识别，Android平台从Android6.0起才提供了官方API，uni-app也是从Android6起支持。对于更低版本的安卓，某些rom私有的指纹识别API，uni-app并不支持。
								success(res) {
									console.log('*******', res, '*******')
									uni.showToast({
										icon: 'none',
										title: '指纹验证成功'
									});
									if (formData.username == "") {
										formData.password = "112233"
										formData.username = "天元邓刚"
									} else {
										formData.password = "112233"
										formData.username = "天元邓刚"
									}
									// 获取直接跳转
									// uni.switchTab({
									// 	url: '/pages/tabbar/tabbar-1/tabbar-1'
									// })
								},
								fail(err) {
									uni.showModal({
										content: '指纹验证失败，errCode：' + err
											.errCode,
										showCancel: false
									});
									console.log(err);
								}
							});
						} else {
							uni.showModal({
								content: '未录入指纹',
								showCancel: false
							});
						}
					}
				});
			}
		});
	}

	// 挂载阶段
	onMounted(() => {
		getUserData();
	});
</script>

<style scoped lang="less">
	.login_body {
		width: 91vw;
		height: 94vh;
		padding: 35rpx;
		background-color: #f0f0f2;
		position: relative;

		.zgn {
			font-size: 60rpx;
			font-weight: 700;
			position: absolute;
			top: 130rpx;
			left: 50%;
			transform: translate(-50%, -50%);
			letter-spacing: 10rpx;
			color: #14afe9;
			padding-top: 126rpx;
			font-family: Arial, Helvetica, sans-serif;
		}

		.ft {
			padding-top: 5rpx;
			font-size: 24rpx;
			letter-spacing: 1rpx;
			color: rgb(200, 210, 210);
			margin-left: -10rpx;
		}

		.login-form {
			margin-top: 280rpx;
			width: 100%;

			.zai-item {
				position: relative;
				display: flex;
				align-items: center;
				margin-top: 5%;
			}
		}

		.icon {
			width: 35upx;
			height: 35upx;
			position: absolute;
			padding-left: 18rpx;
		}

		.zai-input {
			background: #fff;
			margin-top: 0rpx;
			border: 1rpx solid #f0f0f;
			padding: 20rpx 70rpx;
			font-size: 32rpx;
			width: 100%;
			font-weight: 500;
			letter-spacing: 5rpx;
		}

		.input-placeholder,
		.zai-input {
			color: #94afce;
		}

		.zai-btn {
			margin-top: 65rpx;
			display: inline-block;
			background: #14afe9;
			color: #fff;
			border: 0;
			height: 90rpx;
			border-radius: 10rpx;
			font-size: 32rpx;
			width: 400rpx;
		}

		.zai-btn:after {
			border: 0;
		}

		/*按钮点击效果*/
		.zai-btn.button-hover {
			transform: translate(1rpx, 1rpx);
		}

		.btns {
			image {
				width: 100rpx;
				height: 100rpx;
				margin-left: 30rpx;
			}
		}

		.login-form {
			margin-top: 350rpx;
			width: 100%;

			.zai-btn1:after {
				border: 0;
			}


			/*按钮点击效果*/
			.zai-btn1.button-hover {
				transform: translate(1rpx, 1rpx);
			}

			.zai-lun {
				display: flex;
				justify-content: space-between;
				margin-top: 85rpx;
				font-size: 12px;

				.zai-label {
					color: #313c42;
				}
			}

			.third {
				display: flex;
				justify-content: center;
				align-items: center;
				color: #8c8c8c;
				margin-top: 100rpx;
				font-size: 12px;
				padding-bottom: 5%;
				border-bottom: 1rpx solid #8c8c8c;
			}

			.other {
				padding: 50rpx 0;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;

				.othor-item {
					margin: 0 50rpx;

					image {
						width: 60rpx;
						height: 60rpx;
					}
				}
			}
		}
	}
</style>